// package: rewords-server-2024
// filename: hook
// author: diogoxiang@gmail.com
// time: 2024/7/12 上午11:14

package hook

import (
	"context"
	"strings"

	"rewords-server-2024/internal/library/contexts"
	"rewords-server-2024/internal/service"
	"rewords-server-2024/utility/simple"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/glog"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/gogf/gf/v2/text/gstr"
)

// 忽略的请求方式
var ignoredRequestMethods = []string{"HEAD", "PRI", "OPTIONS", "TRACE"}

// accessLog 访问日志
func (s *sHook) accessLog(r *ghttp.Request) {
	if s.isIgnoredRequest(r) {
		return
	}

	var ctx = r.Context()
	if contexts.Get(ctx) == nil {
		return
	}

	// 使用更简洁的时间计算方式
	takeUpTime := gtime.TimestampMilli() - r.EnterTime.TimestampMilli()

	contexts.SetDataMap(ctx, g.Map{
		"request.takeUpTime": takeUpTime,
	})

	simple.SafeGo(ctx, func(ctx context.Context) {
		if err := service.SysLog().AutoLog(ctx); err != nil {
			g.Log().Infof(ctx, "hook accessLog err:%+v", err)
		}
	}, glog.LEVEL_INFO)
}

// isIgnoredRequest 是否忽略请求
func (s *sHook) isIgnoredRequest(r *ghttp.Request) bool {
	method := strings.ToUpper(r.Method)

	// 合并判断条件，提高可读性
	return r.IsFileRequest() || gstr.InArray(ignoredRequestMethods, method)
}
